package com.zhentao.minio.service.impl;


import com.zhentao.minio.config.MinioConfig;
import com.zhentao.minio.config.MinioConfigProperties;
import com.zhentao.minio.service.FileStorageService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.UUID;

@EnableConfigurationProperties(MinioConfigProperties.class)
@Import(MinioConfig.class)
//@Service
public class FileStorageServiceImpl implements FileStorageService {

    @Resource
    private MinioConfigProperties minioConfigProperties;

    @Resource
    private MinioClient minioClient;


//  上传到minio
    @SneakyThrows
    @Override
    public String uploadHtmlFile(String fileName, InputStream inputStream) {

        String fname = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));

        PutObjectArgs poa = PutObjectArgs.builder()
                .bucket(minioConfigProperties.getBucket())
                .object(fileName)
                .contentType("text/html")
                .stream(inputStream, inputStream.available(), -1)//
                .build();

//        上传
        minioClient.putObject(poa);

        String url = minioClient.getObjectUrl(poa.bucket(), poa.object());
        System.out.println(url);

        return url;
    }

//    上传图片
    @SneakyThrows
    @Override
    public String uploadPicFile(String fileName, InputStream inputStream) {

        String fname = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));

        PutObjectArgs poa = PutObjectArgs.builder()
                .bucket(minioConfigProperties.getBucket())
                .object(fileName)
                .contentType("image/jpeg")
                .stream(inputStream, inputStream.available(), -1)//
                .build();

//        上传
        minioClient.putObject(poa);

        String url = minioClient.getObjectUrl(poa.bucket(), poa.object());
        System.out.println(url);

        return url;
    }
}
